package com.tyqx.hashchainbackend.realms;

import com.tyqx.hashchainbackend.service.SysUserService;
import com.tyqx.hashchainbean.module.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.support.DefaultSubjectContext;

import javax.annotation.Resource;
import java.util.Collection;

public class CustomJdbcRealm extends JdbcRealm {

    @Resource
    protected SysUserService sysUserService;

    @Resource
    private SessionDAO sessionDAO;

    //用户认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)throws AuthenticationException{
        //process:js -> dcepUser/login -> Subject.login(UsernamePasswordToken) -> CustomJdbcRealm
        UsernamePasswordToken upToken=(UsernamePasswordToken) token;
        //获取登录账号
        String account=upToken.getUsername();
        //获取所有在线的用户
        Collection<Session> sessions=sessionDAO.getActiveSessions();
        for (Session session:sessions){
            //获取session中用户已经登录的名字
            String loginUserName=String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
            //如果当前登录的用户名已经登录,把之前登录的账号清除,重新登录
            if(account.equals(loginUserName)){
                session.setTimeout(0);
            }
        }
        //通过登录账号查询用户
        SysUser sysUser=null;

        try {
            sysUser=sysUserService.getByUserCode(account);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException();
        }

        //判断是否禁用
        if(sysUser.getUserActivate()==0){
            throw new LockedAccountException();
        }

        //判断用户是否存在
        if(sysUser==null){
            throw new UnknownAccountException();
        }

        String password11=String.valueOf(upToken.getPassword());
        //判断用户名密码是否正确
        if(!sysUser.getUserPassword().equals(String.valueOf(upToken.getPassword()))){
            throw new IncorrectCredentialsException();
        }

        //判断用户是否被禁用

        //用户登录成功,将用户保存到session中
        Session session= SecurityUtils.getSubject().getSession();
        session.setAttribute("sysUser",sysUser);
        //getName()方法自动生成一个realm的名称
        return new SimpleAuthenticationInfo(account,sysUser.getUserPassword(),getName());

    }


}
